#!/usr/bin/python2.5
#
# (c) 2010 - Chip Turner
#
# Apache License, blah blah, it's a few hundred lines of python.

import MySQLdb
import pprint

class AuctionItem(object):
  def __init__(self, json_values):
    json = json_values
    self.auction_id = json["auc"]
    self.bid_copper = json["bid"]
    self.buy_copper = json.get("buy", -1)
    self.item_id = json["id"]
    self.name = json["n"]
    self.quantity = json["quan"]
    self.seller = json["seller"]
    self.remaining_time = json["time"]

class AuctionStorage(object):
  def __init__(self, db):
    self.connection = MySQLdb.connect(db=db, read_default_file="~/.my.cnf")

  def SaveAuction(self, item):
    sql = ("REPLACE INTO Auctions ("
           "id, bid, buy, item_id, "
           "name, quantity, seller, remaining_time, "
           "status, last_seen) "
           "VALUES ("
           "%s, %s, %s, %s, "
           "%s, %s, %s, %s, "
           "%s, NOW())"
           )
    cursor = self.connection.cursor()
    cursor.execute(sql,
                   (item.auction_id, item.bid_copper, item.buy_copper, item.item_id,
                    item.name, item.quantity, item.seller, item.remaining_time, "ACTIVE"))

AUCTION_SCHEMA = """
CREATE TABLE Auctions (
  id integer NOT NULL PRIMARY KEY,
  bid integer NOT NULL,
  buy integer NOT NULL,
  item_id integer NOT NULL,
  name varchar(128) NOT NULL,
  quantity integer NOT NULL,
  seller varchar(32) NOT NULL,
  remaining_time integer NOT NULL,
  status enum('ACTIVE', 'INACTIVE') NOT NULL,
  last_seen datetime NOT NULL,
  INDEX last_seen_idx (last_seen, name),
  INDEX name_idx (name, last_seen)
  INDEX status_idx (status, last_seen)
) ENGINE=InnoDB
"""
